import pymysql


class DB:
    def __init__(self, database, host='localhost', user='root', password='root', port=3306, charset='utf8',
                 cursor_type=pymysql.cursors.Cursor):
        self.__conn = pymysql.connect(host=host, user=user, password=password, port=port, charset=charset,
                                      database=database)
        self.__cursor = self.__conn.cursor(cursor_type)

    def __del__(self):
        self.__cursor.close()
        self.__conn.close()

    def read(self, sql, params_list=None):
        if params_list is None:
            params_list = []
        try:
            rows = self.__cursor.execute(sql, params_list)
            data = self.__cursor.fetchall()
        except Exception as e:
            print('sql语句有问题')
            return None, 'No data'
        return rows, data

    def write(self, sql, params_list=None):
        if params_list is None:
            params_list = []

        try:
            rows = self.__cursor.execute(sql, params_list)
        except Exception as e:
            self.__conn.rollback()
            return 0
        else:
            self.__conn.commit()
        return rows


if __name__ == '__main__':
    pass
